import moment from 'moment'
import { Message } from './resetMessage'
export function transformation(data:number) {//传入时间戳转成文字形式
    let result = ''
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var year = month * 12
    let timeStamp = new Date().getTime()
    var diffValue = timeStamp - data ;//是否要*1000
    if (diffValue < 0) {
        return;
    }
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    let yearC = diffValue / year;
    if (yearC >= 1) {
        result = "" + parseInt(yearC.toString()) + "年前";
    } else if (monthC >= 1) {
        result = "" + parseInt(monthC.toString()) + "月前";
    } else if (weekC >= 1) {
        result = "" + parseInt(weekC.toString()) + "周前";
    } else if (dayC >= 1) {
        result = "" + parseInt(dayC.toString()) + "天前";
    } else if (hourC >= 1) {
        result = "" + parseInt(hourC.toString()) + "小时前";
    } else {
        result = "刚刚";
    }
    return result;
}
export function phoneNumFilter(phone:string) {//将手机号转成 173****1400 的形式
    // 1字符串转化成数组
    let phoneArr = [...phone];
    let str = ''
    // 2.将数组中的4-7位变成*
    phoneArr.map((res, index) => {
        if (index > 2 && index < 7) {
            str += '*';
            // return '*';
        } else {
            str += res;
            // return res;
        }
    });
    return str;
}
export function cardFilter(num:string) {//将银行卡号转成 ****  ****  **** 00000 的形式
        return '****  ****  ****  ' + num.substring(num.length - 4);
}
export function emailFilter(num:string) {//将银行卡号转成 ****  ****  **** 00000 的形式

	let nums;
    let str = num.split('@'),
    _s = ''
if (str[0].length > 3) {
    for (let i = 0; i < str[0].length - 3; i++) {
        _s += '*'
    }
}
nums = str[0].substr(0, 3) + _s + '@' + str[1]
return nums
}
export function copy(object:any){

 return JSON.parse(JSON.stringify(object))
}
export function addDays(date:string,days:number) {//date(年月日时间或者时间戳) days(需要增加的天数) [添加]
    return moment(date).add(days, "day").format('YYYY-MM-DD');
}
export function addMonths(date:string,months:number) {//date(年月日时间或者时间戳) months(需要增加的月数) [添加]
    return moment(date).add(months, "months").format('YYYY-MM-DD');
}
export function addYear(date:string,year:number) {//date(年月日时间或者时间戳) year(需要增加的年数) [添加]
    return moment(date).add(year, "year").format('YYYY-MM-DD');
}
export function subtractDays(date:string,days:number) {//date(年月日时间或者时间戳) days(需要增加的天数) [减少]
    return moment(date).subtract(days, "day").format('YYYY-MM-DD');
}
export function subtractMonths(date:string,months:number) {//date(年月日时间或者时间戳) months(需要增加的月数) [减少]
    return moment(date).subtract(months, "months").format('YYYY-MM-DD');
}
export function subtractYear(date:string,year:number) {//date(年月日时间或者时间戳) year(需要增加的年数) [减少]
    return moment(date).subtract(year, "year").format('YYYY-MM-DD');
}
export function objectMatching(obj:any,obj1:any){//对象与对象相同赋值
    for(let i in obj){
      for(let j in obj1){
          if(i==j){
           obj1[j]=obj[i]
          }
      }
    }
    return obj1
}
export function transferData(data:any,son:number,father:number){
    var r = [];
    var tmpMap:any = {};
    for (var i = 0, l = data.length; i < l; i++) {
      // 以每条数据的id作为obj的key值，数据作为value值存入到一个临时对象里面
      tmpMap[data[i][father]] = data[i];
    }
    // console.log("tmpMap", tmpMap);
    for (i = 0, l = data.length; i < l; i++) {
      var key = tmpMap[data[i][son]];
      // console.log("key", key);
      //循环每一条数据的 fid，假如这个临时对象有这个key值，就代表这个key对应的数据有children，需要Push进去
      //如果这一项数据属于哪个数据的子级
      if (key) {
        // 如果这个数据没有children
        if (!key["children"]) {
          key["children"] = [];
          key["children"].push(data[i]);
          // 如果这个数据有children
        } else {
          key["children"].push(data[i]);
        }
      } else {
        //如果没有这个Key值，就代表找不到属于哪个数据，那就代表没有父级,直接放在最外层
        r.push(data[i]);
      }
    }
    return r;
 }
 export function fileFormat(file:any, file_types = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'png', 'jpg', 'jpeg','JPG','zip'],msg:string){
    const fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
    if (file_types.indexOf(fileType)<0) {
      // this.$message.error('只能pdf格式的文件！')
      if(msg){
        Message({type:'error',message:msg})
      }else{
        Message({type:'error',message:'只能上传图片，文档，表格，压缩包'})
      }
      return false
    }
    return true
  }
  export function addNumbers(num1:any, num2:any) { //加法函数
    const num1Digits = (num1.toString().split('.')[1] || '').length;
    const num2Digits = (num2.toString().split('.')[1] || '').length;
    const maxDigits = Math.max(num1Digits, num2Digits);
   
    const multiplier = Math.pow(10, maxDigits);
    const sum = (num1 * multiplier + num2 * multiplier) / multiplier;
    return sum;
  }
  export function subtractNumbers(minuend:any, subtrahend:any) {
    return addNumbers(minuend, -subtrahend);
  }
  export function formatFileSize(bytes) {
    const kilobyte = 1024;
    const megabyte = kilobyte * 1024;
    if (bytes < kilobyte) {
      return `${bytes} B`;
    } else if (bytes < megabyte) {
      return `${(bytes / kilobyte).toFixed(2)} KB`;
    } else {
      return `${(bytes / megabyte).toFixed(2)} MB`;
    }
  }
  export function derivation(data:any,name:string){//后端给出文件流，前端导出（responseType: 'blob',）
    let title=name
    if(!title){
      let date =parseInt(new Date().getTime() / 1000)
       title=  String(date);
    }
   const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
   // for IE
   if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    const fileName = title + '.xlsx'
    window.navigator.msSaveOrOpenBlob(blob, fileName)
   } else {
    // for Non-IE (chrome, firefox etc.)
    const fileName = title + '.xlsx'
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
   } 
}
export function downZip(l) {
  // const url = l  //l为后台接口返回获取到的文件url地址
  // const link = document.createElement('a')
  // link.setAttribute('download', `${Date.now()}.zip`)// 下载文件名称
  // link.style.display = 'none'// 设置隐藏创建的标签
  // link.href = url
  // document.body.appendChild(link)
  // link.click()// 点击下载
  // link.remove()// 下载后移除
  // this.visible = false
  var blob = new Blob([l], {
    type: "application/zip;charset-UTF-8"
  });
  let date =parseInt(new Date().getTime() / 1000)
 let title=  String(date);
  const blobUrl = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.style.display = "none";
  a.href = blobUrl;
  a.download = title+".zip";
  a.click();
  URL.revokeObjectURL(blobUrl); // 释放内存
}
  export function momentNewDate(){
   return moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
  }
  export function momentDate(name:string){
    return moment(new Date()).format(name)
   }
   export function momentTime(name:string,date:string){
    return moment(date).format(name)
   }
   export function momentStartOf(date,name:string){
    return moment(date).startOf('month').format(name);
   }
   export function momentEndOf(date,name:string){
    return moment(date).endOf('month').format(name);
   }
   export function operateFloat(num1, num2, operator) {
    const num1Digits = (num1.toString().split('.')[1] || '').length;
    const num2Digits = (num2.toString().split('.')[1] || '').length;
    const maxDigits = Math.max(num1Digits, num2Digits);
   
    const baseNum1 = num1 * Math.pow(10, maxDigits);
    const baseNum2 = num2 * Math.pow(10, maxDigits);
   
    let result;
    switch (operator) {
      case '+':
        result = baseNum1 + baseNum2;
        break;
      case '-':
        result = baseNum1 - baseNum2;
        break;
      case '*':
        result = baseNum1 * baseNum2;
        break;
      case '/':
        result = baseNum1 / baseNum2;
        break;
    }
   let num =result / Math.pow(10, maxDigits)
    return num.toFixed(2);
  }
   
